package test.t1;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/*
const iceServers = [{
  urls: "turn:38.147.171.207:3478",
  username: "1729872000:zjn",
  credential: "bViZaK1qK0t3N4o5P6q7R8s9T0u1V2w3X4y5Z6A7B8C9D0E="
}];
* */
public class TurnCredentialGenerator {

    // 与 coturn 配置中的 static-auth-secret 保持一致

    /**
     * 生成临时 TURN 认证凭据
     * @param userId 用户标识（如 "user123"）
     * @param ttlSeconds 有效时间（秒），例如 3600 = 1小时
     * @return String[] {username, password}
     */
    public static String[] generateCredentials(String userId, long ttlSeconds, String SHARED_SECRET) {
        long timestamp = (System.currentTimeMillis() / 1000) + ttlSeconds;
        String username = timestamp + ":" + userId;

        try {
            Mac mac = Mac.getInstance("HmacSHA1");
            SecretKeySpec keySpec = new SecretKeySpec(SHARED_SECRET.getBytes(), "HmacSHA1");
            mac.init(keySpec);

            byte[] hmac = mac.doFinal(username.getBytes());
            String password = Base64.getEncoder().encodeToString(hmac);

            return new String[]{username, password};
        } catch (Exception e) {
            throw new RuntimeException("HMAC-SHA1 signing failed", e);
        }
    }

    // --- 使用示例 ---
    public static void main(String[] args) {
//        String[] credentials = generateCredentials("zjn", 3600 * 2); // 1小时有效

//        System.out.println("Username: " + credentials[0]);
//        System.out.println("Password: " + credentials[1]);
    }
}